package com.xingzhengfan.eurekaclient;

import com.alibaba.druid.pool.DruidDataSource;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import com.dangdang.ddframe.job.config.JobCoreConfiguration;
import com.dangdang.ddframe.job.config.simple.SimpleJobConfiguration;
import com.dangdang.ddframe.job.event.JobEventConfiguration;
import com.dangdang.ddframe.job.event.rdb.JobEventRdbConfiguration;
import com.dangdang.ddframe.job.lite.api.JobScheduler;
import com.dangdang.ddframe.job.lite.config.LiteJobConfiguration;
import com.dangdang.ddframe.job.lite.spring.api.SpringJobScheduler;
import com.dangdang.ddframe.job.reg.zookeeper.ZookeeperConfiguration;
import com.dangdang.ddframe.job.reg.zookeeper.ZookeeperRegistryCenter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

@Configuration
public class JobConfig {

    @Resource
    private OrderJob orderJob;
    @Resource
    private ZookeeperRegistryCenter regCenter;
    @Resource
    private DruidDataSource druidDataSource;
    @Resource
    private JobEventConfiguration jobEventConfiguration;

    @Bean(name = "orderJob")
    public OrderJob orderJob() {
        OrderJob orderJob = new OrderJob();
        return orderJob;
    }

    @Bean(name = "orderJobScheduler", initMethod = "init")
    public JobScheduler orderJobScheduler() {
        return new SpringJobScheduler(orderJob, regCenter, getLiteJobConfiguration(orderJob.getClass(), "0/10 * * * * ? *", 1, "0=A"), jobEventConfiguration);
    }

    @Bean(initMethod = "init")
    public ZookeeperRegistryCenter regCenter() {
        ZookeeperConfiguration configuration = new ZookeeperConfiguration("210.22.173.210:32181", "truecash");
        configuration.setBaseSleepTimeMilliseconds(1000);
        configuration.setMaxSleepTimeMilliseconds(3000);
        configuration.setMaxRetries(3);
        ZookeeperRegistryCenter center = new ZookeeperRegistryCenter(configuration);
        return center;
    }

    @Bean
    public JobEventConfiguration jobEventConfiguration() {
        return new JobEventRdbConfiguration(druidDataSource);
    }

    private LiteJobConfiguration getLiteJobConfiguration(final Class<? extends SimpleJob> jobClass, final String cron, final int shardingTotalCount, final String shardingItemParameters) {
        return LiteJobConfiguration.newBuilder(new SimpleJobConfiguration(JobCoreConfiguration.newBuilder(jobClass.getName(), cron, shardingTotalCount).shardingItemParameters(shardingItemParameters).build(), jobClass.getCanonicalName())).overwrite(true).build();
    }
}
